package com.carnation.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class SessionFilter implements Filter{

	Logger logger = Logger.getLogger(SessionFilter.class);
	
	private List<String> list = new ArrayList<String>();
	
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		String servletPath = httpServletRequest.getServletPath();
		for(String url : list){
			if(servletPath.indexOf(url) > -1){
				logger.info("进入session过滤器->访问路径为[" + servletPath + "]");
				if(httpServletRequest.getSession().getAttribute("sessionInfo") == null){
					httpServletRequest.setAttribute("msg", "您还没有登录或登录超时");
					httpServletRequest.getRequestDispatcher("/login.jsp").forward(httpServletRequest, httpServletResponse);
					return;
				}
				break;
			}
		}
		chain.doFilter(httpServletRequest, httpServletResponse);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		String include = filterConfig.getInitParameter("include");
		if(include != null && !include.isEmpty()){
			StringTokenizer st = new StringTokenizer(include,",");
			list.clear();
			while(st.hasMoreTokens()){
				list.add(st.nextToken());
			}
		}
	}

}
